package com.crazymaker.springcloud.cloud.center.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class DemoFilter extends ZuulFilter {

    static List<String> blackList = Arrays.asList("foo", "bar", "test");

    @Override
    public String filterType() {
        // pre, post, route, error
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        // 如果已经结束，不做任何处理
        if (!context.sendZuulResponse()) {
            return false;
        }
        HttpServletRequest request = context.getRequest();
        boolean b = request.getRequestURI().startsWith("/cloud-zuul/blog/demo");
        if (b)
            return true;
        // 本过滤器不执行
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        // 过滤器的业务逻辑
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String username = request.getParameter("username");
        if (username == null || blackList.contains(username)) {
            log.info(username + " is forbidden:" + request.getRequestURL().toString());
            context.setSendZuulResponse(false);
            try {
                context.getResponse().setContentType("text/html;charset=utf-8");
                context.getResponse().getWriter().write("对不起，您已经进入黑名单");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
